import axios from 'axios'

import router from '@/router'

// 封装业务请求axios
// 1.header注入token
// 2.缺省处理返回状态码

const BaseUrl = '/api'

const getToken = () => {
  return sessionStorage.getItem('token')
}

const defaultConfig = Object.assign({
  timeout: 6000
})

const instance = axios.create(defaultConfig)

instance.defaults.baseURL = BaseUrl

instance.interceptors.request.use(function (config) {
  const token = getToken()
  if (token) {
    config.headers.token = token
  }
  return config
}, function (err) {
  return Promise.reject(err)
})

instance.interceptors.response.use(function (response) {
  if (response.status === 200) {
    // 未登录时重定向
    if (response.data.code === '4002') {
      router.push({ name: 'login' })
      return response
    }

    if (response.data.code === '4003') {
      router.push({ path: response.data.msg })
      return response
    }
  }
  return response
}, function (err) {
  return Promise.reject(err)
})

export default instance
